package com.sunck.common.exception;

import java.lang.reflect.Method;
import java.util.*;

/**
 * 统一返回标准类
 *
 * @author LengChen
 * @version 1.0
 * @date 2020/8/10
 */
public class ResultUtil {
    public static Result error(int code,String msg) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(null);
        result.setDataList(null);
        return result;
    }

    public static Result error(ResultEnum resultEnum) {
        Result result = new Result();
        result.setCode(resultEnum.getCode());
        result.setMsg(resultEnum.getMsg());
        result.setData(null);
        result.setDataList(null);
        return result;
    }

    public static Result success() {
        Result result = new Result();
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMsg(ResultEnum.SUCCESS.getMsg());
        result.setData(null);
        return result;
    }

    public static Result success(Object obj) {
        Result result = new Result();
        result.setCode(200);
        result.setMsg("success");
        result.setData(obj);
        return result;
    }

    public static Result success(ResultEnum resultEnum) {
        Result result = new Result();
        result.setCode(resultEnum.getCode());
        result.setMsg(resultEnum.getMsg());
        result.setData(null);
        return result;
    }




    public static Result successList(List<Object> objList) {
        Result result = new Result();
        result.setCode(200);
        result.setMsg("success");
        result.setDataList(objList);
        return result;
    }


    public static Result getResultEnum(){



        return null;
    }

    /**
     * 根据枚举的字符串获取枚举的值
     *
     * @param code 错误代码
     * @return
     * @throws Exception
     */
    public static Result getResultErrByCode(String code) throws Exception {
        // 1.得到枚举类对象
        Class<Enum> clz = (Class<Enum>) Class.forName("com.sunck.common.exception.ResultEnum");
        // 2.得到所有枚举常量
        Object[] objects = clz.getEnumConstants();
        Method getCode = clz.getMethod("getCode");
        Method getMessage = clz.getMethod("getMsg");
        Result result = null;
        for (Object obj : objects) {
            if(Objects.equals(code,String.valueOf(getCode.invoke(obj)))){
                result = ResultUtil.error(Integer.parseInt(code), String.valueOf(getMessage.invoke(obj)));
                break;
            }

        }
        return result;
    }


}
